import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Movie, Genre, PaginatedResponse, MovieRecommendation, UserStats } from '@/types'
import { movieAPI, recommendationAPI } from '@/services/api'

export const useMoviesStore = defineStore('movies', () => {
  // 响应式状态
  const movies = ref<Movie[]>([])
  const genres = ref<Genre[]>([])
  const currentMovie = ref<Movie | null>(null)
  const recommendations = ref<Recommendation[]>([])
  const popularMovies = ref<Movie[]>([])
  const userStats = ref<UserStats | null>(null)
  const isLoading = ref(false)
  const error = ref<string | null>(null)
  
  // 分页状态
  const pagination = ref({
    count: 0,
    next: null as string | null,
    previous: null as string | null,
    currentPage: 1,
    pageSize: 20,
  })

  // 推荐分页状态
  const recommendationPagination = ref({
    count: 0,
    next: null as string | null,
    previous: null as string | null,
    currentPage: 1,
    pageSize: 20,
  })

  // 搜索参数
  const searchParams = ref({
    search: '',
    genre: '',
    pageSize: 20,
  })

  // 推荐参数
  const recommendationParams = ref({
    algorithm: 'hybrid' as 'user_based' | 'item_based' | 'content_based' | 'hybrid',
    num: 20,
    pageSize: 20,
  })

  // 计算属性
  const hasNextPage = computed(() => !!pagination.value.next)
  const hasPreviousPage = computed(() => !!pagination.value.previous)
  
  // 推荐分页计算属性
  const hasNextRecommendationPage = computed(() => !!recommendationPagination.value.next)
  const hasPreviousRecommendationPage = computed(() => !!recommendationPagination.value.previous)

  // 获取电影列表
  const fetchMovies = async (params?: {
    search?: string
    genre?: string
    page?: number
    page_size?: number
  }) => {
    try {
      isLoading.value = true
      error.value = null
      
      const response = await movieAPI.getMovies(params)
      const data: PaginatedResponse<Movie> = response.data
      
      movies.value = data.results
      pagination.value = {
        count: data.count,
        next: data.next,
        previous: data.previous,
        currentPage: params?.page || 1,
        pageSize: params?.page_size || pagination.value.pageSize,
      }
      
      // 更新搜索参数
      if (params) {
        searchParams.value = {
          search: params.search || '',
          genre: params.genre || '',
          pageSize: params.page_size || searchParams.value.pageSize,
        }
      }
      
      return data
    } catch (err: any) {
      error.value = err.response?.data?.detail || '获取电影列表失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 获取电影详情
  const fetchMovie = async (id: number) => {
    try {
      isLoading.value = true
      error.value = null
      
      const response = await movieAPI.getMovie(id)
      currentMovie.value = response.data
      
      return response.data
    } catch (err: any) {
      error.value = err.response?.data?.detail || '获取电影详情失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 获取电影类型
  const fetchGenres = async () => {
    try {
      const response = await movieAPI.getGenres()
      // 处理分页响应格式
      if (response.data && Array.isArray(response.data.results)) {
        genres.value = response.data.results
      } else if (Array.isArray(response.data)) {
        genres.value = response.data
      } else {
        genres.value = []
      }
      return genres.value
    } catch (err: any) {
      error.value = err.response?.data?.detail || '获取电影类型失败'
      genres.value = []
      throw err
    }
  }

  // 获取热门电影
  const fetchPopularMovies = async (count?: number) => {
    try {
      isLoading.value = true
      error.value = null
      
      const response = await movieAPI.getPopularMovies(count)
      popularMovies.value = response.data
      
      return response.data
    } catch (err: any) {
      error.value = err.response?.data?.detail || '获取热门电影失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 获取推荐电影
  const fetchRecommendations = async (params?: {
    algorithm?: 'user_based' | 'item_based' | 'content_based' | 'hybrid'
    num?: number
    page?: number
    page_size?: number
  }) => {
    try {
      isLoading.value = true
      error.value = null
      
      // 更新推荐参数
      if (params?.algorithm) recommendationParams.value.algorithm = params.algorithm
      if (params?.num) recommendationParams.value.num = params.num
      if (params?.page_size) recommendationParams.value.pageSize = params.page_size
      
      const response = await recommendationAPI.getRecommendations(params)
      
      // 处理分页响应
      if (response.data && typeof response.data === 'object' && 'results' in response.data) {
        recommendations.value = response.data.results
        recommendationPagination.value = {
          count: response.data.count || 0,
          next: response.data.next || null,
          previous: response.data.previous || null,
          currentPage: params?.page || 1,
          pageSize: params?.page_size || recommendationParams.value.pageSize,
        }
      } else {
        // 兼容非分页响应
        recommendations.value = Array.isArray(response.data) ? response.data : []
        recommendationPagination.value = {
          count: recommendations.value.length,
          next: null,
          previous: null,
          currentPage: 1,
          pageSize: recommendationParams.value.pageSize,
        }
      }
      
      return recommendations.value
    } catch (err: any) {
      error.value = err.response?.data?.detail || '获取推荐电影失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 获取用户统计信息
  const fetchUserStats = async () => {
    try {
      const response = await recommendationAPI.getUserStats()
      userStats.value = response.data
      return response.data
    } catch (err: any) {
      error.value = err.response?.data?.detail || '获取用户统计失败'
      throw err
    }
  }

  // 搜索电影
  const searchMovies = async (searchTerm: string, genre = '') => {
    return await fetchMovies({
      search: searchTerm,
      genre,
      page: 1,
      page_size: searchParams.value.pageSize,
    })
  }

  // 加载下一页
  const loadNextPage = async () => {
    if (hasNextPage.value) {
      return await fetchMovies({
        ...searchParams.value,
        page: pagination.value.currentPage + 1,
        page_size: searchParams.value.pageSize,
      })
    }
  }

  // 加载上一页
  const loadPreviousPage = async () => {
    if (hasPreviousPage.value && pagination.value.currentPage > 1) {
      return await fetchMovies({
        ...searchParams.value,
        page: pagination.value.currentPage - 1,
        page_size: searchParams.value.pageSize,
      })
    }
  }

  // 跳转到指定页码
  const loadPage = async (page: number) => {
    const totalPages = Math.ceil(pagination.value.count / pagination.value.pageSize)
    if (page >= 1 && page <= totalPages) {
      return await fetchMovies({
        ...searchParams.value,
        page,
        page_size: searchParams.value.pageSize,
      })
    }
  }

  // 设置每页显示条数
  const setPageSize = async (pageSize: number) => {
    if ([5, 10, 20].includes(pageSize)) {
      return await fetchMovies({
        ...searchParams.value,
        page: 1, // 重置到第一页
        page_size: pageSize,
      })
    }
  }

  // 推荐分页方法
  // 加载推荐下一页
  const loadNextRecommendationPage = async () => {
    if (hasNextRecommendationPage.value) {
      return await fetchRecommendations({
        algorithm: recommendationParams.value.algorithm,
        num: recommendationParams.value.num,
        page: recommendationPagination.value.currentPage + 1,
        page_size: recommendationParams.value.pageSize,
      })
    }
  }

  // 加载推荐上一页
  const loadPreviousRecommendationPage = async () => {
    if (hasPreviousRecommendationPage.value && recommendationPagination.value.currentPage > 1) {
      return await fetchRecommendations({
        algorithm: recommendationParams.value.algorithm,
        num: recommendationParams.value.num,
        page: recommendationPagination.value.currentPage - 1,
        page_size: recommendationParams.value.pageSize,
      })
    }
  }

  // 跳转到推荐指定页码
  const loadRecommendationPage = async (page: number) => {
    const totalPages = Math.ceil(recommendationPagination.value.count / recommendationPagination.value.pageSize)
    if (page >= 1 && page <= totalPages) {
      return await fetchRecommendations({
        algorithm: recommendationParams.value.algorithm,
        num: recommendationParams.value.num,
        page,
        page_size: recommendationParams.value.pageSize,
      })
    }
  }

  // 设置推荐每页显示条数
  const setRecommendationPageSize = async (pageSize: number) => {
    if ([5, 10, 20].includes(pageSize)) {
      return await fetchRecommendations({
        algorithm: recommendationParams.value.algorithm,
        num: recommendationParams.value.num,
        page: 1, // 重置到第一页
        page_size: pageSize,
      })
    }
  }

  // 清除错误
  const clearError = () => {
    error.value = null
  }

  // 重置状态
  const resetState = () => {
    movies.value = []
    currentMovie.value = null
    recommendations.value = []
    popularMovies.value = []
    userStats.value = null
    error.value = null
    pagination.value = {
      count: 0,
      next: null,
      previous: null,
      currentPage: 1,
    }
    searchParams.value = {
      search: '',
      genre: '',
    }
  }

  return {
    // 状态
    movies,
    genres,
    currentMovie,
    recommendations,
    popularMovies,
    userStats,
    isLoading,
    error,
    pagination,
    recommendationPagination,
    searchParams,
    recommendationParams,
    // 计算属性
    hasNextPage,
    hasPreviousPage,
    hasNextRecommendationPage,
    hasPreviousRecommendationPage,
    // 方法
    fetchMovies,
    fetchMovie,
    fetchGenres,
    fetchPopularMovies,
    fetchRecommendations,
    fetchUserStats,
    searchMovies,
    loadNextPage,
    loadPreviousPage,
    loadPage,
    setPageSize,
    loadNextRecommendationPage,
    loadPreviousRecommendationPage,
    loadRecommendationPage,
    setRecommendationPageSize,
    clearError,
    resetState,
  }
})